package com.yinuo.quartz;

import com.yinuo.common.SystemWaiter;
import com.yinuo.entity.DocBinary;
import com.yinuo.repository.DocRepository;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileClearQuartz extends QuartzJobBean {

    private Logger logger = LoggerFactory.getLogger(FileClearQuartz.class);

    @Autowired
    private DocRepository linuxDocRepository;

    //Pattern ATTR_PATTERN = Pattern.compile("<img\\b[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic)\\b)[^>]*>", Pattern.CASE_INSENSITIVE);
    Pattern Image_ATTR_PATTERN = Pattern.compile("/uploadedFiles\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic)\\b)", Pattern.CASE_INSENSITIVE);
    /**
     * 执行清理无引用的文件 定时任务
     *
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException{
        logger.info("[ ******* file clear quartz execute begin ******* ]");
        //图片清理
        imageClean();
        //视频清理

        logger.info("[******* file clear quartz execute end ******* ]");
    }




    private void imageClean(){
        List<DocBinary> linuxDocBinaries = linuxDocRepository.findAll();
        List<String> exixtedFiles = new ArrayList<String>(20);
        for(int i=0;i<linuxDocBinaries.size();i++){
            DocBinary li = linuxDocBinaries.get(i);
            String s = null;
            try {
                s = new String(li.getContent(),"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if(StringUtils.hasText(s)){
                Matcher matcher = Image_ATTR_PATTERN.matcher(s);
                while (matcher.find()) {
                    exixtedFiles.add(matcher.group(0));
                }
            }
        }
        logger.info(String.format("[********** Images reference in database(%d) : %s**********]",exixtedFiles.size(),exixtedFiles.toString()));
        //执行图片清理函数
        SystemWaiter.clearImageFile(exixtedFiles);
    }


}